import XEUtils from 'xe-utils';
import { watch, ref, reactive, nextTick } from 'vue';
import { TableColTypes } from '@/base/pojo/TableColType.js'
import { linkUrlRender, columnRender, columnFormatter } from '../cfg/table-render.jsx';

import { TableDataType } from '@/base/pojo/TableDataType.js'

export const defaultSeqColumn = { type: 'seq', width: 50, title: '序号', align: 'center' };
export const defaultBoxColumn = TableColTypes.getBoxTypesCol();

export const useColumnsConfig = ({ props, attrs, emits, slots, gridRef, gridOptions }) => {

	// 相关的字段信息
	const columnsInfo = reactive({
		// 选框类型，默认为复选框
		boxMode: '',
		// 处理后的字段
		columns: [],
		// 排序字段
		seqColumns: [],
		// 选框字段
		boxColumns: [],
		// 字段的插槽
		columnSlots: [],
		// 需要合计的字段
		totaledFields: [],
		// 合计字段对应的格式化配置
		totaledFormats: {},
		// 需要平均数的字段
		averageFields: [],
		// 平均数字段对应的格式化配置
		averageFormats: {},
		// 不采用tooltip提示的字段
		noTooltipColumns: [],
	});

	// 监听传递的字段配置
	watch(
		[
			() => props.columns,
			() => props.seqConfig,
			() => props.boxConfig,
		],
		([newX, newY]) => {
			initColumnsConfig()
		},
		{ deep: true, immediate: false }
	)

	watch(
		[
			() => props.totaled,
			() => props.average
		],
		([newX, newY]) => {
			nextTick(() => {
				gridRef.value.updateFooter()
			})
		},
		{ deep: true, immediate: false }
	)

	/**
	 * 初始化字段配置
	 */
	const initColumnsConfig = () => {
		const columns = getColumns(XEUtils.clone(props.columns, true));
		const seqColumns = getSeqColumn(props);
		const boxColumns = getBoxColumn(props);
		columnsInfo.columns = columns;
		columnsInfo.seqColumns = seqColumns;
		columnsInfo.boxColumns = boxColumns;
		// 给表格字段属性赋值
		gridOptions['columns'] = [...boxColumns, ...seqColumns, ...columns];
		// 校验组件插槽是否存在
		validCloumnSlots(columnsInfo.columnSlots);
		// console.log('columnsInfo', props, columnsInfo)
	};

	/**
	 * 获取表格定义字段信息
	 *
	 * @param {Array} targetColumns 原始字段
	 * @returns Object {
	 * 	columns: 处理后的字段
	 * }
	 */
	const getColumns = (targetColumns = []) => {
		const columns = targetColumns.map((col) => {
			const { columnSlots } = columnsInfo
			// 表头文字居中
			if (!col.hasOwnProperty('headerAlign')) col['headerAlign'] = 'center';
			// 统计合计字段
			if (col.totaled) {
				columnsInfo.totaledFields.push(col.field)
				if (col.hasOwnProperty('formatRule') && col.formatRule && TableDataType.NUMBER.includeFormat(col.formatRule)) {
					columnsInfo.totaledFormats[col.field] = col.formatRule
				} else {
					columnsInfo.totaledFormats[col.field] = props.numberFormat
				}
			};
			// 统计平均数字段
			if (col.average) {
				columnsInfo.averageFields.push(col.field)
				if (col.hasOwnProperty('formatRule') && col.formatRule && TableDataType.NUMBER.includeFormat(col.formatRule)) {
					columnsInfo.averageFormats[col.field] = col.formatRule
				} else {
					columnsInfo.averageFormats[col.field] = props.numberFormat
				}
			};
			// 存在超链接的情况
			if (col.hasOwnProperty('linkUrl') && col.linkUrl) {
				const colSlots = col['slots'] || {};
				col['slots'] = { ...colSlots, default: params => linkUrlRender(params, col) };
			}
			// 统计插槽配置
			if (col.hasOwnProperty('slots')) {
				const { default : def, edit, header, content } = col.slots
				if (def && XEUtils.isString(def) && !columnSlots.includes(def)) {
					columnSlots.push(def)
				}
				if (edit && XEUtils.isString(edit) && !columnSlots.includes(edit)) {
					columnSlots.push(edit)
				}
				if (header && XEUtils.isString(header) && !columnSlots.includes(header)) {
					columnSlots.push(header)
				}
				if (content && XEUtils.isString(content) && !columnSlots.includes(content)) {
					columnSlots.push(content)
				}
			}
			// 处理格式化 -- TODO 自定义字段 formatRule
			if (col.hasOwnProperty('formatRule') && col.formatRule) {
				col['formatter'] = params => columnFormatter(params, col);
			} else {
				if (col.hasOwnProperty('formatFunc') && col.formatFunc) {
					col['formatter'] = params => columnFormatter(params, col);
				}
			}
			// 处理渲染函数
			if (col.hasOwnProperty('renderFunc') &&  col.renderFunc) {
				if (col.hasOwnProperty('slots')) {
					col.slots['default'] = params => columnRender(params, col)
				} else {
					col['slots'] = {
						default: params => columnRender(params, col)
					}
				}
			}

			// 处理tooltip -- TODO 自定义字段 tooltip
			if (col.hasOwnProperty('tooltip') && !col.tooltip) {
				columnsInfo.noTooltipColumns.push(col.field)
			}
			// 处理合并表头
			if (col.children && col.children.length) {
				col['sortable'] = false;
				col.children = getColumns(col.children);
			} else {
				if (!col.hasOwnProperty('sortable')) col['sortable'] = true;
			}
			return col;
		});
		return columns;
	};

	/**
	 * 获取需要字段信息
	 *
	 * @param {Boolean, String} seqConfig 序号配置
	 * @returns 序号字段
	 */
	const getSeqColumn = ({ seqConfig }) => {
		if (!seqConfig) return [];
		let finalFlag = false
		let finalColumn = XEUtils.clone(defaultSeqColumn, true);;
		if (seqConfig && XEUtils.isString(seqConfig) && TableColTypes.includeFixedTypes(seqConfig)) {
			finalFlag = true
			finalColumn['fixed'] = seqConfig;
		} else if (seqConfig && XEUtils.isBoolean(seqConfig)) {
			finalFlag = seqConfig
		} else if (seqConfig && XEUtils.isObject(seqConfig)) {
			if (!seqConfig.enabled) return []
			// 校验参数
			if (!XEUtils.isBoolean(seqConfig.enabled)) {
				console.warn(`seqConfig配置参数不正确，enabled只能为布尔类型，请确认！`);
				return []
			}
			finalFlag = seqConfig.enabled
			if (seqConfig.fixed) {
				if (TableColTypes.includeFixedTypes(seqConfig.fixed)) {
					finalColumn['fixed'] = seqConfig.fixed;
				} else {
					console.warn(`seqConfig配置参数不正确，fixed只能为${TableColTypes.getFixedTypesValue().join('|')}，请确认！`);
					return [];
				}
			}
		}
		return finalFlag ? [finalColumn] : [];
	};

	/**
	 * 获取选框字段信息
	 *
	 * @param {Object} param { seqConfig: 序号配置 boxConfig: 选框配置 }
	 * @returns 选框字段
	 */
	const getBoxColumn = ({ seqConfig, boxConfig }) => {
		let finalMode = '';
		let finalColumn = null;
		if (boxConfig && XEUtils.isString(boxConfig)) {
			if (TableColTypes.includeBoxTypes(boxConfig)) {
				finalMode = boxConfig;
				finalColumn = XEUtils.clone(defaultBoxColumn[boxConfig], true);
			}
			if (TableColTypes.includeFixedTypes(boxConfig)) {
				finalMode = 'checkbox';
				finalColumn = XEUtils.clone(defaultBoxColumn[finalMode], true);
				finalColumn['fixed'] = boxConfig
			}
		}
		if (boxConfig && XEUtils.isBoolean(boxConfig)) {
			finalMode = 'checkbox';
			finalColumn = XEUtils.clone(defaultBoxColumn[finalMode], true);
		}
		if (boxConfig && XEUtils.isObject(boxConfig)) {
			if (!boxConfig.hasOwnProperty('mode')) {
				console.warn('boxConfig配置格式不正确，请确认！');
				return [];
			}
			if (!TableColTypes.includeBoxTypes(boxConfig.mode)) {
				console.warn('boxConfig配置参数不正确，mode只能为checkbox|radio，请确认！');
				return [];
			}
			finalMode = boxConfig.mode;
			finalColumn = XEUtils.clone(defaultBoxColumn[finalMode], true);
			if (boxConfig.hasOwnProperty('fixed')) {
				const fixed = boxConfig.fixed;
				if (fixed && XEUtils.isString(fixed) && TableColTypes.includeFixedTypes(fixed)) {
					finalColumn['fixed'] = fixed;
				}
				if (fixed && XEUtils.isBoolean(fixed)) {
					finalColumn['fixed'] = 'left';
				}
			}
		}
		// 如果序号浮动，选框默认同序号一同浮动
		if (boxConfig && seqConfig && finalColumn && XEUtils.isString(seqConfig) && TableColTypes.includeFixedTypes(seqConfig)) {
			finalColumn['fixed'] = seqConfig;
		}
		columnsInfo.boxMode = finalMode || 'checkbox'
		return finalColumn ? [finalColumn] : [];
	};

	/**
	 * 校验插槽字段信息
	 * @param {Array} columnSlots 插槽字段
	 */
	const validCloumnSlots = (columnSlots = []) => {
		if (columnSlots && columnSlots.length) {
			columnSlots.forEach(slotName => {
				if (!slots[slotName]) console.warn(`表格中插槽 "${slotName}" 不存在！`)
			});
		}
	}

	return {
		columnsInfo,
		initColumnsConfig,
	};
};
